package com.cqhfan.core.utils;

import cn.hutool.core.util.StrUtil;
import com.cqhfan.core.constans.BizConstants;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author 眭传洪
 * @create 2025-07-25 2:04
 */
public class WebUtil {

    public static boolean isGatewayRequest() {
        String header = getHeader(BizConstants.REQUEST_FROM_HEADER);
        if (StrUtil.isBlank(header)) {
            return false;
        }
        return header.equals(BizConstants.GATEWAY_ORIGIN_NAME);
    }

    public static ServletRequestAttributes getServletRequestAttributes() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return (ServletRequestAttributes) requestAttributes;
    }

    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
        if (servletRequestAttributes == null) {
            return null;
        }
        return servletRequestAttributes.getRequest();
    }

    public static String getHeader(String headerName) {
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return null;
        }
        return getHttpServletRequest().getHeader(headerName);
    }

}
